package com.zy.yun.controller;

import com.alibaba.fastjson.JSONObject;
import com.zy.yun.base.common.RestResult;
import com.zy.yun.base.constant.Const;
import com.zy.yun.base.entity.User;
import com.zy.yun.provider.service.IResService;
import com.zy.yun.utils.RedisUtil;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 王彦委
 * @Description: 后台用户登录
 * @Date: 22:17 2019/10/25
 */
@RestController
public class LoginController {


    @Value("${security.oauth2.client.accessTokenUri}")
    private String accessTokenUri;

    @Autowired
    private RedisUtil<User,List> RedisUtil;

    @Autowired
    private IResService resService;

    private static final CloseableHttpClient httpclient = HttpClients.createDefault();

    /**
     * @Author: 王彦委
     * @Description: 用户登录, 去认证中心认证。注：现在是认证与网关放在一个服务中，后期根据需要可以分开
     * @Date: 22:18 2019/10/25
     */
    @RequestMapping("login")
    public RestResult login(String username, String password) throws IOException {


        List<NameValuePair> formparams = new ArrayList<NameValuePair>();

        formparams.add(new BasicNameValuePair("grant_type", "password"));
        formparams.add(new BasicNameValuePair("scope", "all"));
        formparams.add(new BasicNameValuePair("password", password));
        formparams.add(new BasicNameValuePair("username", username));
        formparams.add(new BasicNameValuePair("client_id", "client_1"));
        formparams.add(new BasicNameValuePair("client_secret", "123456"));

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
        //去认证中心，请求 access_token
        HttpPost httpPost = new HttpPost(accessTokenUri);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = httpclient.execute(httpPost);
        HttpEntity result = response.getEntity();
        String s = EntityUtils.toString(result);
        System.err.println(s);

        // TODO: 2019/11/6 0006  先做如下简单处理，后期统一错误码
        //转化json,判断返回结果 错误结果： {"error":"invalid_grant","error_description":"Bad credentials"}
        JSONObject jsonObject = JSONObject.parseObject(s);
        if (null != jsonObject.get("error")) {
            return RestResult.buildError("用户名或密码错误！");
        }

        //用户拥有的url链接权限
        //根据用户对应角色id,查询用户对应的权限,
        User user =RedisUtil.getObject(username,User.class);
        String token = jsonObject.getString("token_type") + " " + jsonObject.getString("access_token");
        //把用户信息与token关联起来
        RedisUtil.setMapObject(Const.TOKEN_MAP_NAME,token,user);


        // 正常结果： {"access_token":"22c6b951-7bf4-4b32-93c0-ab9403f274e1","token_type":"bearer","refresh_token":"933ba940-e9ae-41bb-a5cc-cfc26fd3ca9e","expires_in":5710,"scope":"all"}
        return RestResult.buildSuccess(s);
    }

    /**
     * @Author: 王彦委
     * @Description: 用户退出
     * @Date: 12:55 2019/11/6 0006
     */
    @RequestMapping("quit")
    public RestResult logout() throws IOException {
        return RestResult.buildSuccess();

    }


}
